//Set up some constants
var BASE_URL = 'http://localhost:8080/Grailsmaps';
var ITEMS_PER_PAGE = 10;

//Set up some form level variables
var stateId = "";
var searchText;
var currentPage = 0;


/* jQuery initialization function */
$(document).ready(function() {

    $(window).unload(function () {
        GUnload();
    });

    $.ajaxSetup({ cache: false });

    /* Global event handlers - easiest way to respond to ajax events
     * These also can take parameters with information on the request */
    $('#ajax-status').ajaxStart(function() {
        $(this).text('Requesting...');
        $(this).show();
        });

    $('#ajax-status').ajaxComplete(function() {
              $(this).text('Request complete');
              $(this).fadeOut('slow');
        });

     $('#ajax-status').ajaxError(function() {
        $(this).text('Ajax error occurred');
        $(this).fadeIn();
        });


    /* Could have an id for the search button for easier location. */
    $('#search-form input[type=button]').click(function() {
        currentPage = 0;
        search($('input[name=searchText]').val());
    });

    /* populate states on initial load
    This is a convenience version of the generic .ajax method
    * can inspect the json with fireBug*/
    $.getJSON(BASE_URL + "/state/list?format=json&jsoncallback=?", loadStatesResponse);


});


/* Populate json state results */
function loadStatesResponse(data) {
    /* add the state <li> nodes */
    $.each(data.states, function(index, state) {
        $("<li>" + state.stateName + '</li>').appendTo($('#state-list ul')).data('id', state.id);//note chaining
    });

    /* add the click handler to the list.
     * Might have used hyperlinks here, ie6 ie7 quirks issues */
    $('#state-list li').each(function() {
        $(this).click(function() {
            $('#city-header').text('Cities in ' + $(this).text());
            stateId = $(this).data('id');
            $('#state-list li').removeClass("selected-state");
            $(this).addClass("selected-state");
            searchText = "";
            $('input[name=searchText]').val("");
            currentPage = 0;
            loadCities(stateId);

        });
    });

}
/* load cities using the current page as the offset */
function loadCities(stateId) {
    var offset = currentPage * ITEMS_PER_PAGE;
    listCitiesJson(offset);
}

/* Search button click  handler*/
function search(searchString) {
    searchText = searchString;
    listCitiesJson(0);
}


/* use clicks a pagination link */
function loadPage(pageLink) {
    /* Calculate the new page number to load */
    var newPage;
    var newPageText = $(pageLink).text();
    if (newPageText == 'Next') {
        newPage = currentPage + 1;
    }
    else if (newPageText == 'Prev') {
        newPage = currentPage - 1;
    }
    else {
        //convert to base 0
        newPage = parseInt(newPageText) - 1;
    }
    /* convert to an offset and load the json */
    var offset = (newPage) * ITEMS_PER_PAGE;
    listCitiesJson(offset);
    currentPage = newPage;


}


function listCitiesJson(offset) {
    $.getJSON(BASE_URL + "/state/listCities/" + stateId + "?jsoncallback=?",
    { format:"json", max: ITEMS_PER_PAGE,offset:offset,searchText:searchText },
            loadCitiesResponse);

}

/* Process json for a city list */
function loadCitiesResponse(data) {

    /* remove all table rows except header */
    $('table#city-list tr').not(':first-child').remove();

    if (data.cities.length > 0) {
        initPagination(data.numberOfCities, currentPage, ITEMS_PER_PAGE);
        loadMapLocation(data.cities[0].latitude, data.cities[0].longitude)
        displayCityList();
    }
    else {
        $(".pagination-wrapper").hide();
    }
    /* create the new table
     * More optimal to create a single html string,
     * then style the result or insert existing classes */
    $.each(data.cities, function(index, city) {
        var tr = $('<tr>');
        $(tr).data("id", city.id);
        var tdCity = $("<td>" + city.cityName + "</td>");
        $(tdCity).css({color:'blue'}).appendTo(tr);
        if (stateId == null | stateId == '') {
            var tdState = $("<td id='state-" + city.state.id + "'>" + city.state.stateAbbrev + "</td>");
            $(tdState).appendTo(tr);
        }
        $(tr).appendTo($('table#city-list'));
    });
    if (stateId == null | stateId == '') {
        $('th#state-header').show();
        $('#city-header').hide();
    }
    else {
        $('th#state-header').hide();
        $('#city-header').show();
    }


    $('table#city-list tr').click(function () {
        loadCity($(this).data("id"));
    }
            ).addClass("city-link");


}

/* Do a json call for a single city by id */
function loadCity(id) {

    $.getJSON(BASE_URL + "/city/show/" + id + "?jsoncallback=?",
    { format:"json", max: ITEMS_PER_PAGE,offset:0 },
            loadCityResponse);
}

/* handler to load a single city json data */
function loadCityResponse(city) {

    if (stateId == '') {
        $('#back-to-search').text('Back to search');
    }
    else {
        $('#back-to-search').text('Back to ' + city.state.stateName);
    }
    $('#back-to-search').click(function() {
        loadCities(stateId);
    });


    /* Build the html for the city information block
     * string based is faster than appending individual elements but nasty */
    var newHTML = "<h2>" + city.cityName + "," + city.state.stateAbbrev + "</h2>   \
                    <div class='form-row'><label>Latitude</label>\
                        <span>" + city.latitude + "</span>\
                   </div>        \
                    <div class='form-row'><label>Longitude</label>\
                         <span>" + city.longitude + "</span>\
                    </div>  ";


    $('div#city-wrapper').children().not(':first-child').remove();
    $('div#city-wrapper').append($(newHTML));
    addMapMarker(city.latitude, city.longitude)
    displayCityDetail();


}

/* some google maps functionality */
function loadMapLocation(latitude, longitude) {

    var map = new google.maps.Map2(document.getElementById("map"));
    map.setCenter(new GLatLng(latitude, longitude), 6);
    map.setUIToDefault();
}


function addMapMarker(latitude, longitude) {

    var map = new google.maps.Map2(document.getElementById("map"));
    map.setCenter(new GLatLng(latitude, longitude), 6);
    map.setUIToDefault();

    var point = new GLatLng(latitude, longitude);
    map.addOverlay(new GMarker(point));
}

/* hide or show elements based on context
 is it easier to just load anew page?
 */
function displayCityList() {
    $('#search-form').show();
    $('#city-list-wrapper').show();
    $('table#city-list').show();
    $('div#app-header').hide();
    $('div#city-wrapper').hide();
    $(".pagination-wrapper").show();


}


function displayCityDetail() {
    $('#search-form').hide();
    $('table#city-list').hide();
    $('div#city-wrapper').show();
    $('div#app-header').hide();
    $(".pagination-wrapper").hide();
}